/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 *
 * CustomerPremisesServiceImpl.java
 */
package com.yixun.qfbao.xf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yixun.common.page.Page;
import com.yixun.qfbao.constant.StringConstant;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.mapper.CommissionRulesMapper;
import com.yixun.qfbao.mapper.OverdueConfigMapper;
import com.yixun.qfbao.mapper.PartnerInfoMapper;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.model.initdto.InitCPCustomerDto;
import com.yixun.qfbao.model.whdto.ItemInfoDto;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.mapper.CustomerPremisesMapper;
import com.yixun.qfbao.xf.mapper.FollowUpListMapper;
import com.yixun.qfbao.xf.mapper.PremisesMapper;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.FollowUpList;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.*;
import com.yixun.qfbao.xf.model.enums.CommissionStatusEnum;
import com.yixun.qfbao.xf.model.enums.*;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.FollowUpListService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service("customerPremisesService")
public class CustomerPremisesServiceImpl implements CustomerPremisesService {
	private static Logger logger = LoggerFactory.getLogger(CustomerPremisesServiceImpl.class);

	@Autowired
	private CustomerPremisesMapper mapper;

	@Autowired
	private PremisesMapper premisesMapper;

	@Autowired
	private PartnerInfoService partnerInfoService;

	@Autowired
	private PremisesService premisesService;

	@Autowired
	private FollowUpListService followUpListService;

	@Autowired
	private SMSUtil smsUtil;

	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private SmsHistoryService smsHistoryService;

	@Autowired
	private CustomerPremisesMapper customerPremisesMapper;

	@Autowired
	private DepartmentDao departmentDao;

	@Autowired
	private FollowUpListMapper followUpListMapper;

	@Autowired
	private CommissionRulesMapper commissionRulesMapper;

	@Autowired
	private PartnerInfoMapper partnerInfoMapper;

	@Autowired
	private FollowUpListMapper followListMapper;

	@Autowired
	private CommissionService commissionService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private OverdueConfigMapper overdueConfigMapper;
	@Autowired
	@Lazy
	private CustomerService customerService;

	// 本变量是提供给报备查询使用，在报备查询后会进行remove，其他方法请谨慎使用。
    public static final ThreadLocal<String> LOGIN_TYPE = new ThreadLocal<>();
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Override
	@Transactional(readOnly = true)
	public Page<CustomerPremises> getPageModel(CustomerPremisesDto entity, int begin, int end) {
		Integer total = 0;
		if(!SystemIdEnum.ASSISTANT.getCode().equals(LOGIN_TYPE.get())) {
			total = mapper.count(entity);
		}
		LOGIN_TYPE.remove();
		List<CustomerPremises> rows = mapper.list(entity, begin, end);
		// 加载楼盘信息
		if (null != rows && rows.size() > 0) {
		    List<Long> premisesIds = rows.stream()
                    .map(CustomerPremises::getPremisesId)
                    .collect(Collectors.toList());
            PremisesDto premisesDto = new PremisesDto();
            premisesDto.setPremisesIds(premisesIds);
		    List<Premises> premisesList = premisesService.selectSimpleListByDto(premisesDto);
		    Map<Long, Premises> premisesMap = premisesList.stream()
					.collect(Collectors.toMap(Premises::getId, Function.identity()));

		    List<Long> staffCompanyIds = rows.stream()
                    .map(CustomerPremises::getStaffCompanyId)
                    .collect(Collectors.toList());
		    CompanyDto companyDto = new CompanyDto();
		    companyDto.setIds(staffCompanyIds);
		    List<CompanyDto> companyList = companyService.selectListByIds(companyDto);
		    Map<Long, String> companyNameMap = companyList.stream()
                    .collect(Collectors.toMap(CompanyDto::getId, CompanyDto::getCompanyName));

		    List<Long> partnerIds = new ArrayList<>();
		    for(CustomerPremises customerPremises: rows){
                partnerIds.add(customerPremises.getStaffId());
                partnerIds.add(customerPremises.getPartnerId());
            }
		    PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
		    partnerInfoDto.setIds(partnerIds);
		    List<PartnerInfo> partnerInfoList = partnerInfoService.selectWholeListByDto(partnerInfoDto);
			Map<Long, PartnerInfo> partnerInfoMap = partnerInfoList.stream()
                    .collect(Collectors.toMap(PartnerInfo::getId, Function.identity()));

			List<Long> deptIds = partnerInfoList.stream()
                    .map(PartnerInfo::getDeptId)
                    .collect(Collectors.toList());
			DepartmentDto departmentDto = new DepartmentDto();
			departmentDto.setDeptIds(deptIds);
			List<Department> departmentList = departmentDao.selectListByDto(departmentDto);
            Map<Long, Department> departmentMap = departmentList.stream()
                    .collect(Collectors.toMap(Department::getId, Function.identity()));

		    for (CustomerPremises customerPremises : rows) {
				Premises premises = premisesMap.get(customerPremises.getPremisesId());//premisesMapper.selectById(customerPremises.getPremisesId());
				if (Objects.nonNull(premises)) {
					customerPremises.setCheckSwitch(premises.getCheckSwitch());
					customerPremises.setPremisesName(premises.getName());
					if (StringUtils.isBlank(premises.getProjectCodeM2())) {
						customerPremises.setIsToM2("2"); // 当M2项目编号为空时表示非M2合作商户，不能转客
					}
				}

				// 加载案场人员姓名
				if (Objects.nonNull(customerPremises.getPartnerId())) {
					PartnerInfo partnerInfo = partnerInfoMap.get(customerPremises.getPartnerId()); //partnerInfoService.selectById(customerPremises.getPartnerId());
					if(Objects.nonNull(partnerInfo)){
						customerPremises.setPartnerName(partnerInfo.getAccountName());
						customerPremises.setPartnerPhone(partnerInfo.getPhone());
					}
				}

				String confirmStatus = customerPremises.getConfirmStatus();
				customerPremises.setCommission("0");
				if (null != customerPremises.getCommissionAmount() && CommissionStatusEnum.has_commission.getNo().equals(confirmStatus)) {
					customerPremises.setCommission(customerPremises.getCommissionAmount() + "");
				}
				StringBuilder departmentName = new StringBuilder();
				String companyName = "";
				if (null != customerPremises.getStaffCompanyId()) {
					companyName = companyNameMap.get(customerPremises.getStaffCompanyId());
                    departmentName.append(companyName);
				}
				if (null != customerPremises.getStaffId()) {
					PartnerInfo partnerInfo = partnerInfoMap.get(customerPremises.getStaffId()); //partnerInfoService.selectById(customerPremises.getStaffId());
					if (null != customerPremises && partnerInfo != null) {
						customerPremises.setClientSource(partnerInfo.getAccountName());
						customerPremises.setStaffPhone(partnerInfo.getPhone());
						customerPremises.setStaffName(partnerInfo.getAccountName());

						customerPremises.setPrincipal(getPrincipal(customerPremises.getPrincipalId()));// 获取对接人信息
						//获取报备人部门名/门店组别
						Department department = departmentMap.get(partnerInfo.getDeptId()); //departmentDao.selectById(partnerInfo.getDeptId());
						if (Objects.nonNull(department) && !department.getDepartmentName().equals(companyName)) {
							departmentName.append(" - " + department.getDepartmentName());
						}
					}
				}
				customerPremises.setStaffCompanyName(departmentName.toString());

				if (StringUtils.isNotBlank(customerPremises.getCustomerStatus())) {
					customerPremises.setCusNewStatusName(customerPremises.getCusNewStatusName());
				}
				// 是否被分配过
				Long partnerId = customerPremises.getPartnerId();
				customerPremises.setIsDist("F");
				if (null != partnerId) {
					customerPremises.setIsDist("T");
				}

				// 计算带看保护时间
				Date visitProtectTime = customerPremises.getVisitProtectTime();
				Calendar calendar = Calendar.getInstance();
				// 默认报备: 非带看保护期中......
				customerPremises.setVisitProtecting(false);
				// 判断是否特殊报备: 特殊报备记录,皆为非带看保护中记录....
				String reportType = customerPremises.getReportType();
				if (StringUtils.isEmpty(reportType) || ReportTypeEnum.type_1.getNo().equals(reportType)) {
					if (null != visitProtectTime) {
						// 比较带看保护时间是否大于当前时间
						// 大于当前时间: 带看保护中 小于当前时间: 已过保护时间,可操作记录
						if (visitProtectTime.compareTo(calendar.getTime()) > 0) {
							customerPremises.setVisitProtecting(true);
						}
					}
				}
				// 判断客户电话是否隐号展示
				customerPremises.setMobileHidden(Boolean.FALSE);
				if(entity.getShowFullNumber() != null
						&& StringUtils.isNotEmpty(customerPremises.getMobile())
						&& customerPremises.getMobile().indexOf(StringConstant.THREE_STAR) < 0
						&& Boolean.FALSE.equals(entity.getShowFullNumber())){
					String hideMobile = ReportWayEnum.convertMobileByReportWay(customerPremises.getMobile(), ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo());
				    customerPremises.setMobile(hideMobile);
					customerPremises.setMobileHidden(Boolean.TRUE);
				}
			}
		}
		Page<CustomerPremises> msr = new Page<CustomerPremises>(total, rows);
		return msr;
	}

	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Override
	@Transactional(readOnly = true)
	public Page<CustomerPremisesDto> getMyPageModel(CustomerPremisesDto entity, int begin, int end) {
		Integer total = mapper.myCount(entity);
		List<CustomerPremisesDto> rows = mapper.myList(entity, begin, end);

		SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		// 加载楼盘信息
		if (null != rows && rows.size() > 0) {
			List<Long> staffIds = rows.stream().filter(item -> Objects.nonNull(item.getStaffId()))
					.map(CustomerPremisesDto::getStaffId)
					.collect(Collectors.toList());
			PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
			partnerInfoDto.setIds(staffIds);
			List<PartnerInfo> partnerInfoList = partnerInfoService.selectListByDto(partnerInfoDto);
			Map<Long, PartnerInfo> partnerInfoMap = partnerInfoList.stream()
					.collect(Collectors.toMap(PartnerInfo::getId, Function.identity()));

			List<Long> companyIds = rows.stream().filter(item -> Objects.nonNull(item.getStaffCompanyId()))
					.map(CustomerPremisesDto::getStaffCompanyId)
					.collect(Collectors.toList());
			CompanyDto companyDto = new CompanyDto();
			companyDto.setIds(companyIds);
			List<Company> companyList = companyService.selectListByDto(companyDto);
			Map<Long, Company> companyMap = companyList.stream()
					.collect(Collectors.toMap(Company::getId, Function.identity()));

			for (CustomerPremisesDto customerPremises : rows) {
				String commissionWay = customerPremises.getCommissionWay();
				if (StringUtils.isNotEmpty(commissionWay)) {
					customerPremises.setCommissionWayName(CommissionWayEnum.getDescByNo(commissionWay));
				}
				if (null != customerPremises.getCommissionAmount()) {
					customerPremises.setCommission(customerPremises.getCommissionAmount() + "");
				} else {
					customerPremises.setCommission("待定");
				}
				if (null != customerPremises.getStaffId()) {
					PartnerInfo partnerInfo = partnerInfoMap.get(customerPremises.getStaffId());
					if (Objects.nonNull(partnerInfo)) {
						customerPremises.setClientSource(partnerInfo.getAccountName());
						customerPremises.setStaffPhone(partnerInfo.getPhone());
						customerPremises.setStaffName(partnerInfo.getAccountName());
					}
				}
				if (null != customerPremises.getStaffCompanyId()) {
					Company company = companyMap.get(customerPremises.getStaffCompanyId());
					if (Objects.nonNull(company)) {
						customerPremises.setStaffCompanyName(company.getCompanyName());
						customerPremises.setCardNumber(company.getCardNumber());
					}
				}

				if (StringUtils.isNotBlank(customerPremises.getCustomerStatus())) {
					customerPremises.setCusNewStatusName(customerPremises.getCustomerStatusName());
				}
				// 计算带看保护时间
				Date visitProtectTime = customerPremises.getVisitProtectTime();
				Calendar calendar = Calendar.getInstance();
				// 默认报备: 非带看保护期中......
				customerPremises.setVisitProtecting(false);
				// 判断是否特殊报备: 特殊报备记录,皆为非带看保护中记录....
				String reportType = customerPremises.getReportType();
				if (StringUtils.isEmpty(reportType) || ReportTypeEnum.type_1.getNo().equals(reportType)) {
					if (null != visitProtectTime) {
						// 比较带看保护时间是否大于当前时间
						// 大于当前时间: 带看保护中 小于当前时间: 已过保护时间,可操作记录
						if (visitProtectTime.compareTo(calendar.getTime()) > 0) {
							customerPremises.setVisitProtecting(true);
						}
					}
				}
				if (customerPremises.getUpdateTime() != null) {
					customerPremises.setFormatCreateTime(sft.format(customerPremises.getUpdateTime()));
				} else {
					customerPremises.setFormatCreateTime(sft.format(customerPremises.getCreateTime()));
				}
				// 代报备时，案场人员的名字不会为空
				if (StringUtils.isNotBlank(customerPremises.getAssistantName())) {
					customerPremises.setReportType("案场代报备");
				} else {
					customerPremises.setReportType("经纪人报备");
					if (StringUtils.isNotBlank(customerPremises.getReportPhone())){
						customerPremises.setStaffPhone(customerPremises.getReportPhone());
					}
				}
				// 设置佣金状态
				if (StringUtils.isNotBlank(customerPremises.getCommissionStatus())) {
					customerPremises.setCommissionName(CommissionStatusEnum.getByNo(customerPremises.getCommissionStatus()).getDes());
				} else {
					// 为空时设置为待结佣
					customerPremises.setCommissionName(CommissionStatusEnum.no_commission.getDes());
				}
				// 设置按揭状态
				if (StringUtils.isNotBlank(customerPremises.getMortgageStatus())) {
					customerPremises.setMortgageStatusName(MortgageStatusEnum.getByNo(customerPremises.getMortgageStatus()).getDes());
				}
			}
		}

		Page<CustomerPremisesDto> msr = new Page<CustomerPremisesDto>(total, rows);
		msr.setPageInfo(total, begin, begin + end);
		return msr;
	}

	/**
	 * @param entity 搜索条件 特殊需求（不对premises表中的del_falg做限制）
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Override
	@Transactional(readOnly = true)
	public Page<CustomerPremisesDto> getMyPageModel2(CustomerPremisesDto entity, int begin, int end) {
		Integer total = mapper.seleceCPCountList(entity);
		List<CustomerPremisesDto> rows = mapper.seleceCPList(entity, begin, end);
		if(CollectionUtils.isNotEmpty(rows)){
			for (CustomerPremisesDto customerPremises : rows) {
				if(Objects.nonNull(customerPremises.getHopeVisitTime())){
					customerPremises.setFormatHopeVisitTime(DateUtils.DateToString(customerPremises.getHopeVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
				}
				String commissionWay = customerPremises.getCommissionWay();
				if (StringUtils.isNotEmpty(commissionWay)) {
					customerPremises.setCommissionWayName(CommissionWayEnum.getDescByNo(commissionWay));
				}
				if (null != customerPremises.getCommissionAmount()) {
					customerPremises.setCommission(customerPremises.getCommissionAmount() + "");
				} else {
					customerPremises.setCommission("待定");
				}
				if (StringUtils.isNotBlank(customerPremises.getCustomerStatus())) {
					customerPremises.setCusNewStatusName(customerPremises.getCustomerStatusName());
				}
				// 计算带看保护时间
				Date visitProtectTime = customerPremises.getVisitProtectTime();
				Calendar calendar = Calendar.getInstance();
				// 默认报备: 非带看保护期中......
				customerPremises.setVisitProtecting(false);
				// 判断是否特殊报备: 特殊报备记录,皆为非带看保护中记录....
				String reportType = customerPremises.getReportType();
				if (StringUtils.isEmpty(reportType) || ReportTypeEnum.type_1.getNo().equals(reportType)) {
					if (null != visitProtectTime) {
						// 比较带看保护时间是否大于当前时间
						// 大于当前时间: 带看保护中 小于当前时间: 已过保护时间,可操作记录
						if (visitProtectTime.compareTo(calendar.getTime()) > 0) {
							customerPremises.setVisitProtecting(true);
						}
					}
				}

				customerPremises.setFormatCreateTime(DateUtils.DateToString(customerPremises.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM));
				// 代报备时，案场人员的名字不会为空
				if (StringUtils.isNotBlank(customerPremises.getAssistantName())) {
					customerPremises.setReportType("案场代报备");
				} else {
					customerPremises.setReportType("经纪人报备");
					if(StringUtils.isNotBlank(customerPremises.getReportPhone())){
						customerPremises.setStaffPhone(customerPremises.getReportPhone());
					}
				}
				// 设置佣金状态
				if (StringUtils.isNotBlank(customerPremises.getCommissionStatus())) {
					customerPremises.setCommissionName(CommissionStatusEnum.getByNo(customerPremises.getCommissionStatus()).getDes());
				} else {
					// 为空时设置为待结佣
					customerPremises.setCommissionName(CommissionStatusEnum.no_commission.getDes());
				}
				// 设置按揭状态
				if (StringUtils.isNotBlank(customerPremises.getMortgageStatus())) {
					customerPremises.setMortgageStatusName(MortgageStatusEnum.getByNo(customerPremises.getMortgageStatus()).getDes());
				}
				// 判断客户电话是否隐号展示
				customerPremises.setMobileHidden(Boolean.FALSE);
				String mobile = customerPremises.getMobile();
				if(entity.getShowFullNumber() != null
						&& StringUtils.isNotEmpty(customerPremises.getMobile())
						&& !mobile.contains(StringConstant.THREE_STAR)
						&& Boolean.FALSE.equals(entity.getShowFullNumber())){
					mobile = ReportWayEnum.convertMobileByReportWay(mobile, ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo());
					customerPremises.setMobile(mobile);
					customerPremises.setMobileHidden(Boolean.TRUE);
				}
				// 判断是否隐藏经纪人电话
                if(Objects.nonNull(entity.getHideAgentPhone()) && Boolean.TRUE.equals(entity.getHideAgentPhone())){
                	String staffPhone = ReportWayEnum.convertMobileByReportWay(customerPremises.getStaffPhone(), ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo());
                    customerPremises.setStaffPhone(staffPhone);
                }
			}
		}

		Page<CustomerPremisesDto> msr = new Page<CustomerPremisesDto>(total, rows);
		return msr;
	}

	/**
	 * 查询列表
	 *
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<CustomerPremises> selectListByDto(CustomerPremisesDto entity) {
		return mapper.selectListByDto(entity);
	}

	/**
	 * 查询单个
	 *
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public CustomerPremises selectByDto(CustomerPremisesDto entity) {
		return mapper.selectByDto(entity);
	}

	/**
	 * @param id 搜索条件
	 * @return 分页记录
	 */
	@Override
	public CustomerPremises selectById(Long id) {
		if (id != null) {
			return mapper.selectById(id);
		}
		return null;
	}

	@Override
	public CustomerPremises selectByMobile(String mobile) {
		return mapper.selectByMobile(mobile);
	}

	/**
	 * @param id 搜索条件
	 * @return 分页记录
	 */
	@Override
	public CustomerPremisesDto selectByMyId(Long id) {
		if (id != null) {
			return mapper.selectByMyId(id);
		}
		return null;
	}

	/**
	 * @param entity 新增记录的详细信息
	 * @return 新增行数
	 */
	@Override
	public CustomerPremisesDto create(CustomerPremisesDto entity) {
		if (entity.getCreateTime() == null) {
			entity.setCreateTime(Calendar.getInstance().getTime());
		}
		//添加更新时间
		entity.setUpdateTime(Calendar.getInstance().getTime());
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		mapper.add(entity);

		// 新增报备,未指定客户时.报备绑定客户信息
		customerService.addReport2BindCustomer(entity);
		return entity;
	}

	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	@Override
	public int update(CustomerPremisesDto entity) {
		/**
		 * 临时解决方案,先查一遍再修改
		 * 金额为空或为零时,查一下原始金额
		 */
		if(null == entity.getDealAmount() || entity.getDealAmount().compareTo(BigDecimal.ZERO)==0){
			CustomerPremises cusPre = mapper.selectById(entity.getId());
			entity.setDealAmount(cusPre.getDealAmount());
		}

		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edit(entity);
	}
	/**
	 * 紧急处理预案
	 * @param entity
	 * @return
	 */
	@Override
	public int newUpdate(CustomerPremisesDto entity) {
		CustomerPremises cusPre = mapper.selectById(entity.getId());
		if ("0".equals(cusPre.getVisitState()) || "1".equals(cusPre.getVisitState()) || "2".equals(cusPre.getVisitState()) || "3".equals(cusPre.getVisitState())) {
			cusPre.setVisitState(Integer.valueOf(cusPre.getVisitState()) + 1 +"");
		}
		entity.setVisitState(cusPre.getVisitState());
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edit(entity);
	}

	@Override
	public int updateStatus(CustomerPremisesDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.edit(entity);
	}

	@Override
	public int updateCustomerByCustomerIds(CustomerPremisesDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.updateCustomerByCustomerIds(entity);
	}

	@Override
	public int edits(CustomerPremises customerPremises, String ids) {
		return mapper.edits(customerPremises, ids);
	}

	/**
	 * @param entity 待删除的记录信息
	 * @return 删除行数
	 */
	@Override
	public int destroy(CustomerPremisesDto entity) {
		return mapper.del(entity);
	}

	/**
	 * @param entity 新增或更新
	 * @return 新增行数
	 */
	@Override
	public int saveOrUpdate(CustomerPremisesDto entity) {
		if (entity != null && entity.getId() != null) {
			return update(entity);
		} else {
			create(entity);
			return 1;
		}
	}

	/**
	 * @param entity 根据pojo搜索如果主键为空则返回它本身
	 * @return 一行记录或本身
	 */
	@Override
	public CustomerPremises selectBy(CustomerPremises entity) {
		if (entity != null && entity.getId() != null) {
			return mapper.selectById(entity.getId());
		}
		return entity;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String reSubmit(String accountType, Long cusPremisesId, Long staffId, String remark) {
		CustomerPremises customerPremises = mapper.selectById(cusPremisesId);
		String result = "0";
		String oldCustomerStatus = customerPremises.getCustomerStatus();
		if (!accountType.equals(MechanismAccountTypeEnum.mechanism.getNo()) && customerPremises.getStaffId().compareTo(staffId) != 0) {
			return "-2";
		} else {
			// 申诉数量>0,不能再次申诉
			if (customerPremises.getComplaintsNumber() != null && customerPremises.getComplaintsNumber().compareTo(0L) > 0) {
				return "-3";
			}
			// 带看保护时间
			Calendar visitProtectCalendar = getVisitProtectCalendar(customerPremises.getPremisesId(), null);
			customerPremises.setVisitProtectTime(visitProtectCalendar.getTime());

			customerPremises.setAppealTime(Calendar.getInstance().getTime());
			customerPremises.setAppealReason("【申诉】" + remark);
			customerPremises.setProcessStatus(ProcessStatusEnum.pending.getNo());
			customerPremises.setCustomerStatus(CustomerStatusEnum.normal.getNo());
			if (null != customerPremises.getComplaintsNumber()) {
				customerPremises.setComplaintsNumber(customerPremises.getComplaintsNumber() + 1);
			} else {
				customerPremises.setComplaintsNumber(1L);
			}
			mapper.edit(customerPremises);
		}
		FollowUpListDto fulDto = new FollowUpListDto();
		fulDto.setCustomerPremisesId(customerPremises.getId());
		fulDto.setStaffId(customerPremises.getStaffId());
		fulDto.setOldConfirmStatus(customerPremises.getConfirmStatus());
		fulDto.setNewConfirmStatus(ConfirmStatusEnum.confirm.getNo());
		fulDto.setOldCustomerStatus(oldCustomerStatus);
		fulDto.setNewCustomerStatus(CustomerStatusEnum.normal.getNo());
		fulDto.setFollowType(FollowTypeEnum.CHANNEL.getNo());
		String newRemark = "";
		if (StringUtils.isNotBlank(remark)) {
			newRemark = remark;
		}
		fulDto.setRemark("【申诉】" + newRemark);
		fulDto.setFollowUpType(FollowUpEnum.status_transfer.getNo());
		followUpListService.create(fulDto);
		return result;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.yixun.qfbao.xf.service.CustomerPremisesService#selectCustomerPremisesByStaffId(java.lang.Long)
	 */
	@Override
	public CustomerPremisesDto selectCustomerPremisesByStaffId(PartnerInfo pi, Boolean isturn, String commissionFlag) {
		
		CustomerPremisesDto entity = new CustomerPremisesDto();
		entity.setStaffId(pi.getId());
		// 如果是公司类型账户，则查询公司信息
		if ("0".equals(pi.getAccountType())) {
			entity.setStaffId(null);
			entity.setStaffCompanyId(pi.getHigherid());
		}
		int reportCount = mapper.count(entity);
		entity.setReportCount(reportCount);
		if ("0".equals(commissionFlag)) {
			//当前公司不需要佣金信息，设置为0后直接返回
			entity.setCommissionAmount("0");
			entity.setTotalAmount(new BigDecimal(0));
			entity.setHasbalance(new BigDecimal(0));
			entity.setHasnobalance(new BigDecimal(0));
			return entity;
		}
		
		CustomerPremises customerPremises = mapper.selectcCustomerPremisesCommissionByDto(entity);
		
		//未查询到报备信息
		if (customerPremises == null) {
			entity.setCommissionAmount("0");
			entity.setTotalAmount(new BigDecimal(0));
			entity.setHasbalance(new BigDecimal(0));
			entity.setHasnobalance(new BigDecimal(0));
			return entity;
		}
		BigDecimal totalAmount = customerPremises.getAgentCommission();
		BigDecimal hasbalance = customerPremises.getAgentReceivedCommission();
		BigDecimal hasnobalance = customerPremises.getAgentPendingCommission();
		BigDecimal commissionTotol = totalAmount;
		// 已获佣金合计：该商户所有员工【已结佣】佣金之和
		if (null != isturn && isturn) {// 转换成万元
			entity.setCommissionAmount(String.valueOf(commissionTotol));
			entity.setTotalAmount(totalAmount.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP));
			entity.setHasbalance(hasbalance.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP));
			entity.setHasnobalance(hasnobalance.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP));
		} else {
			entity.setCommissionAmount(String.valueOf(commissionTotol));
			entity.setTotalAmount(totalAmount);
			entity.setHasbalance(hasbalance);
			entity.setHasnobalance(hasnobalance);
		}
		return entity;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.yixun.qfbao.xf.service.CustomerPremisesService#selectCustomerPremisesListByStaffId(java.lang.Long)
	 */
	@Override
	public Page<CustomerPremisesDto> selectCustomerPremisesListByStaffId(CustomerPremisesDto dto, 
			Integer pageNo, Integer pageSize, String loginType) {
		if (StringUtils.isBlank(dto.getCustomerStatus())) {
			dto.setNopremises("true");
		}
		//  分销小程序的查询逻辑为 佣金为0的不纳入展示
		//  待结佣：待结佣金 = 总佣金数， 且不为0
		//  部分结佣， 待结佣金值小于佣金总额
		//  已结佣： 待结佣金 = 总佣金数,且不为0
		String commissionStatus = dto.getCommissionStatus();
		dto.setCommissionStatus("");
		if(CommissionStatusEnum.all_commission.getNo().equals(commissionStatus)) {
			dto.setSql("( rc.agent_pending_commission != 0 or rc.agent_received_commission != 0)");
		}else if (CommissionStatusEnum.has_commission.getNo().equals(commissionStatus)) {
			if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType)) {
				dto.setSql("(rc.agent_received_commission = rc.agent_commission and rc.agent_commission != 0)");
			}else {
				// 查询未结佣数据，因为在未结佣状态下报备表中佣金状态为空（报备流程图标显示，所以设置为空），所以在这里进行处理
				// 待结佣，则查询条件为待结佣金额不为0
				dto.setSql("(rc.agent_received_commission != 0)");
			}
			
		}else if (CommissionStatusEnum.no_commission.getNo().equals(commissionStatus)) {
			if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType)) {
				dto.setSql("(rc.agent_pending_commission = rc.agent_commission and rc.agent_commission != 0)");
			}else {
				// 已结佣，则设置已结佣金额不为0
				dto.setSql("(rc.agent_pending_commission != 0)");
			}
		}else if (CommissionStatusEnum.some_commission.getNo().equals(commissionStatus)) {
			if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType)) {
				dto.setSql("(rc.agent_received_commission < rc.agent_commission && rc.agent_received_commission != 0)");
			}
		}
		
		
		logger.info("selectCustomerPremisesListByStaffId params: {}", JSONObject.toJSONString(dto));
		int count = mapper.countDto(dto);
		List<CustomerPremisesDto> rows = mapper.listDto(dto, pageNo, pageSize);
		logger.info("selectCustomerPremisesListByStaffId rows size: {}", rows.size());
		SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
		if(!SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType)) {
			// TODO 修改多次数据库查询为一次
			for (CustomerPremisesDto cusDto : rows) {
				if (CommissionStatusEnum.has_commission.getNo().equals(dto.getCommissionStatus())) {
					// 如果是已结佣，获取结佣时间
					FollowUpListDto entity = new FollowUpListDto();
					entity.setCustomerPremisesId(cusDto.getId());
					entity.setNewCommissionStatus(CommissionStatusEnum.has_commission.getNo());
					entity.setSql("old_commission_status is null");
					FollowUpList list = followUpListService.selectByDto(entity);
					if (list != null && list.getCreateTime() != null) {
						cusDto.setJieYongDate(sft.format(list.getCreateTime()));
					}
				}
			}
		}
		Page<CustomerPremisesDto> msr = new Page<CustomerPremisesDto>(count, rows);
		return msr;
	}

	/**
	 * 查询数量
	 *
	 * @param entity 搜索条件
	 */
	@Override
	public int count(CustomerPremisesDto entity) {
		return mapper.count(entity);
	}

	@Override
	public int overTradeTimeCount(CustomerPremisesDto entity) {
		return mapper.overTradeTimeCount(entity);
	}

	/**
	 * 查询列表
	 *
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<CustomerPremises> findCustomerListByStaffId(CustomerPremisesDto entity) {
		return mapper.findCustomerListByStaffId(entity);
	}

	@Override
	public List<CustomerPremisesDto> selectRecommendCusByPremises(CustomerPremisesDto entity) {
		return mapper.selectRecommendCusByPremises(entity);
	}

	@Override
	public List<CustomerPremisesDto> selectAdminRecommendCusByPremises(CustomerPremisesDto entity) {
		return mapper.selectAdminRecommendCusByPremises(entity);
	}

	@Override
	public String toReport(Long cusPremisesId, Long staffId, String remark) {
		try {
			CustomerPremises cusPre = mapper.selectById(cusPremisesId);
			if (cusPre == null) {
				return "3";
			}
			Premises premises = premisesMapper.selectById(cusPre.getPremisesId());
			if (premises == null) {
				return "4";
			}
			CustomerPremisesDto cpDto = new CustomerPremisesDto();
			List<String> customerStatusList = new ArrayList<String>();
			customerStatusList.add(CustomerStatusEnum.normal.getNo());
			customerStatusList.add(CustomerStatusEnum.not_visited.getNo());
			customerStatusList.add(CustomerStatusEnum.has_visited.getNo());
			/* customerStatusList.add(CustomerStatusEnum.paid_in.getNo()); */
			CustomerPremisesDto cusPreDto = new CustomerPremisesDto();
			cusPreDto.setMobile(cusPre.getMobile());
			cusPreDto.setPremisesId(cpDto.getPremisesId());
			cusPreDto.setCustomerStatusList(customerStatusList);
			// 该手机号对应客户存在的未完结报备记录条数
			int validCount = mapper.count(cusPreDto);
			if (validCount > 0) {
				return "2";
			}
			/*
			 * String oldCustomerStatus = cusPre.getCustomerStatus(); String oldConfirmStatus =
			 * cusPre.getConfirmStatus(); // 更新记录 cusPre.setCustomerStatus(CustomerStatusEnum.normal.getNo()); //带看保护时间
			 * Calendar visitProtectCalendar = getVisitProtectCalendar(cusPre.getPremisesId(), null);
			 * cusPre.setVisitProtectTime(visitProtectCalendar.getTime()); cusPre.setId(cusPre.getId());
			 * mapper.edit(cusPre);
			 */
			// 重新发起生成一条新的记录
			CustomerPremises customerPremises = new CustomerPremises();
			BeanUtils.copyProperties(cusPre, customerPremises);
			if (cusPre.getAfreshNum() == null) {
				// customerPremises.setAfreshNum(Long.parseLong("1"));
			} else {
				return "-1";
			}
			customerPremises.setId(null);
			Date hopeVisitTime = customerPremises.getHopeVisitTime();
			Calendar calendar = Calendar.getInstance();
			// 期望带看时间小于系统当前时间。期望带看时间以当前时间为加一天
			if (Objects.nonNull(hopeVisitTime) && hopeVisitTime.getTime() < calendar.getTime().getTime()) {
				calendar.add(Calendar.DAY_OF_MONTH, 1);
				customerPremises.setHopeVisitTime(calendar.getTime());
			}
			customerPremises.setDisableType("");
			customerPremises.setComplaintsNumber(null);
			customerPremises.setStaffCompanyId(cusPre.getStaffCompanyId());
			customerPremises.setCustomerStatus(CustomerStatusEnum.normal.getNo());
			customerPremises.setConfirmStatus(ConfirmStatusEnum.confirm.getNo());
			customerPremises.setPremisesSource(cusPre.getPremisesSource());
			int cu = mapper.add(customerPremises);
			// 原记录 afresh_num +1
			cusPre.setAfreshNum(1l);
			mapper.edit(cusPre);

			// 写带状态跟进记录
			FollowUpList followUpList = new FollowUpList();
			followUpList.setCreateTime(Calendar.getInstance().getTime());
			followUpList.setCustomerPremisesId(customerPremises.getId());
			followUpList.setNewConfirmStatus(customerPremises.getConfirmStatus());
			followUpList.setNewCustomerStatus(customerPremises.getCustomerStatus());
			followUpList.setStaffId(customerPremises.getStaffId());
			followUpList.setFollowType(FollowTypeEnum.CHANNEL.getNo());
			followUpList.setRemark("【报备客户】");
			followUpList.setFollowUpType(FollowUpEnum.status_transfer.getNo());
			followUpListMapper.add(followUpList);
			/*
			 * FollowUpListDto fulDto = new FollowUpListDto(); fulDto.setCustomerPremisesId(cusPre.getId());
			 * fulDto.setStaffId(cusPre.getStaffId()); fulDto.setOldConfirmStatus(oldConfirmStatus);
			 * fulDto.setNewConfirmStatus(ConfirmStatusEnum.confirm.getNo());
			 * fulDto.setOldCustomerStatus(oldCustomerStatus);
			 * fulDto.setNewCustomerStatus(CustomerStatusEnum.normal.getNo());
			 * fulDto.setFollowType(FollowTypeEnum.CHANNEL.getNo()); String newRemark = "";
			 * if(StringUtils.isNotBlank(remark)){ newRemark = remark; } fulDto.setRemark("【报备客户】重新发起," + newRemark);
			 * followUpListService.create(fulDto);
			 */
			return "0";
		} catch (Exception e) {
			logger.error("toReport 异常: {}", e);
			return "-1";
		}
	}

	@Override
	public List<CustomerPremisesDto> selectCustomerByPremises(CustomerPremisesDto entity) {
		return mapper.selectCustomerByPremises(entity);
	}

	/**
	 * 待申诉记录
	 *
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Override
	@Transactional(readOnly = true)
	public Page<CustomerPremisesDto> getAppealPageModel(CustomerPremisesDto entity, int begin, int end) {
		Integer total = mapper.appealCount(entity);
		List<CustomerPremisesDto> rows = mapper.appealList(entity, begin, end);
		Page<CustomerPremisesDto> msr = new Page<CustomerPremisesDto>(total, rows);
		return msr;
	}

	@Override
	public Page<AgentRankReport> queryAgentRankReport(AgentRankReportParam agentRankReportParam, int begin, int end) {
		List<AgentRankReport> reportList = new ArrayList<AgentRankReport>();
		Page<AgentRankReport> page = new Page<AgentRankReport>();
		reportList = mapper.queryAgentRankReportByCompanyId(agentRankReportParam, begin, end);
		int count = mapper.countAgentRankReportByCompanyId(agentRankReportParam);
		page.setRows(reportList);
		page.setPageInfo(count, begin, begin + end);
		// 查询报备客户
		/*
		 * List<AgentRank> agentRankOneList=mapper.queryAgentRankReportByfollow(agentRankReportParam); Map<Long, String>
		 * oneMap = new HashMap<Long, String>(); int count = 0; boolean changeList = true; for(AgentRank rank
		 * :agentRankOneList){ count = rank.getCustomerCount(); oneMap.put(rank.getStaffId(), rank.getStaffName() + "|"
		 * + rank.getCustomerCount()); } //默认用来循环的Map List<AgentRank> foreachList = agentRankOneList; if(count > 0){
		 * changeList = false; } //报备成功客户 List<String> customerStatusList=new ArrayList<String>();
		 * //customerStatusList.add(CustomerStatusEnum.valid.getNo());
		 * //agentRankReportParam.setCustomerStatusList(customerStatusList); agentRankReportParam.setSql(
		 * " ful.new_customer_status = 1 and ful.old_customer_status != ful.new_customer_status "); List<AgentRank>
		 * agentRankTwo=mapper.queryAgentRankReportByfollow(agentRankReportParam); Map<Long, String> twoMap = new
		 * HashMap<Long, String>(); for(AgentRank rank :agentRankTwo){ if(changeList){ count += rank.getCustomerCount();
		 * } twoMap.put(rank.getStaffId(), rank.getStaffName() + "|" + rank.getCustomerCount()); } if(count > 0 &&
		 * changeList){ foreachList = agentRankTwo; changeList = false; } //到访客户 customerStatusList.clear();
		 * customerStatusList.add(CustomerStatusEnum.has_visited.getNo()); //
		 * agentRankReportParam.setCustomerStatusList(customerStatusList); agentRankReportParam.setSql(
		 * " ful.new_customer_status = 6 and ful.old_customer_status != ful.new_customer_status "); List<AgentRank>
		 * agentRankThree=mapper.queryAgentRankReportByfollow(agentRankReportParam); Map<Long, String> threeMap = new
		 * HashMap<Long, String>(); for(AgentRank rank :agentRankThree){ if(changeList){ count +=
		 * rank.getCustomerCount(); } threeMap.put(rank.getStaffId(), rank.getStaffName() + "|" +
		 * rank.getCustomerCount()); } if(count > 0 && changeList){ foreachList = agentRankThree; changeList = false; }
		 * //重置客户状态 agentRankReportParam.setCustomerStatusList(null); List<String> confirmStatusList=new
		 * ArrayList<String>(); //认筹客户 // confirmStatusList.add(ConfirmStatusEnum.payDeposit.getNo()); //
		 * agentRankReportParam.setConfirmStatusList(confirmStatusList); agentRankReportParam.setSql(
		 * " ful.new_confirm_status = 1 and ful.old_confirm_status != ful.new_confirm_status "); List<AgentRank>
		 * agentRankFour=mapper.queryAgentRankReportByfollow(agentRankReportParam); Map<Long, String> fourMap = new
		 * HashMap<Long, String>(); for(AgentRank rank :agentRankFour){ if(changeList){ count +=
		 * rank.getCustomerCount(); } fourMap.put(rank.getStaffId(), rank.getStaffName() + "|" +
		 * rank.getCustomerCount()); } if(count > 0 && changeList){ foreachList = agentRankFour; changeList = false; }
		 * //认购客户 confirmStatusList.clear(); // confirmStatusList.add(ConfirmStatusEnum.subscribe.getNo()); //
		 * agentRankReportParam.setConfirmStatusList(confirmStatusList); agentRankReportParam.setSql(
		 * " ful.new_confirm_status = 2 and ful.old_confirm_status != ful.new_confirm_status "); List<AgentRank>
		 * agentRankFive=mapper.queryAgentRankReportByfollow(agentRankReportParam); Map<Long, String> fiveMap = new
		 * HashMap<Long, String>(); for(AgentRank rank :agentRankFive){ if(changeList){ count +=
		 * rank.getCustomerCount(); } fiveMap.put(rank.getStaffId(), rank.getStaffName() + "|" +
		 * rank.getCustomerCount()); } if(count > 0 && changeList){ foreachList = agentRankFive; changeList = false; }
		 * //签约客户 confirmStatusList.clear(); // confirmStatusList.add(ConfirmStatusEnum.sign.getNo()); //
		 * agentRankReportParam.setConfirmStatusList(confirmStatusList); agentRankReportParam.setSql(
		 * " ful.new_confirm_status = 3 and ful.old_confirm_status != ful.new_confirm_status "); List<AgentRank>
		 * agentRankSix=mapper.queryAgentRankReportByfollow(agentRankReportParam); Map<Long, String> sixMap = new
		 * HashMap<Long, String>(); for(AgentRank rank :agentRankSix){ if(changeList){ count += rank.getCustomerCount();
		 * } sixMap.put(rank.getStaffId(), rank.getStaffName() + "|" + rank.getCustomerCount()); } if(count > 0 &&
		 * changeList){ foreachList = agentRankSix; changeList = false; }
		 *
		 * for (int i = 0; i < foreachList.size(); i++) { AgentRankReport row=new AgentRankReport(); int top = i+1;
		 * row.setTopValue("No."+top);
		 *
		 * AgentRank rank = (AgentRank)foreachList.get(i); //报备客户 AgentRank agentRank1 = new AgentRank();
		 * agentRank1.setCustomerCount(0); String one = oneMap.get(rank.getStaffId()); if(StringUtils.isNotBlank(one)){
		 * String[] ranks = one.split("\\|"); agentRank1.setStaffName(ranks[0]);
		 * agentRank1.setCustomerCount(Integer.parseInt(ranks[1])); } row.setAgentRankOne(agentRank1);
		 *
		 * //报备客户成功 AgentRank agentRank2 = new AgentRank(); agentRank2.setCustomerCount(0); String two =
		 * twoMap.get(rank.getStaffId()); if(StringUtils.isNotBlank(two)){ String[] ranks = two.split("\\|");
		 * agentRank2.setStaffName(ranks[0]); agentRank2.setCustomerCount(Integer.parseInt(ranks[1])); }
		 * row.setAgentRankTwo(agentRank2);
		 *
		 * //到访客户 AgentRank agentRank3 = new AgentRank(); agentRank3.setCustomerCount(0); String three =
		 * threeMap.get(rank.getStaffId()); if(StringUtils.isNotBlank(three)){ String[] ranks = three.split("\\|");
		 * agentRank3.setStaffName(ranks[0]); agentRank3.setCustomerCount(Integer.parseInt(ranks[1])); }
		 * row.setAgentRankThree(agentRank3);
		 *
		 * //到访客户 AgentRank agentRank4 = new AgentRank(); agentRank4.setCustomerCount(0); String four =
		 * fourMap.get(rank.getStaffId()); if(StringUtils.isNotBlank(four)){ String[] ranks = four.split("\\|");
		 * agentRank4.setStaffName(ranks[0]); agentRank4.setCustomerCount(Integer.parseInt(ranks[1])); }
		 * row.setAgentRankFour(agentRank4);
		 *
		 * //到访客户 AgentRank agentRank5 = new AgentRank(); agentRank5.setCustomerCount(0); String five =
		 * fiveMap.get(rank.getStaffId()); if(StringUtils.isNotBlank(five)){ String[] ranks = five.split("\\|");
		 * agentRank5.setStaffName(ranks[0]); agentRank5.setCustomerCount(Integer.parseInt(ranks[1])); }
		 * row.setAgentRankFive(agentRank5);
		 *
		 * //到访客户 AgentRank agentRank6 = new AgentRank(); agentRank6.setCustomerCount(0); String six =
		 * sixMap.get(rank.getStaffId()); if(StringUtils.isNotBlank(six)){ String[] ranks = six.split("\\|");
		 * agentRank6.setStaffName(ranks[0]); agentRank6.setCustomerCount(Integer.parseInt(ranks[1])); }
		 * row.setAgentRankSix(agentRank6);
		 *
		 * reportList.add(row); }
		 */
		return page;
	}

	@Override
	public Page<CustomerConversionReport> queryCustomerConversionReport(CustomerConversionReportParam customerConversionReportParam, int begin,
		int end) {
		Page<CustomerConversionReport> page = new Page<CustomerConversionReport>();
		List<CustomerConversionReport> rows = mapper.queryCustomerConversionReport(customerConversionReportParam, begin, end);
		int count = mapper.countCustomerConversionReport(customerConversionReportParam);
		page.setRows(rows);
		page.setPageInfo(count, begin, begin + end);
		return page;
	}

	@Override
	public List<ChannelEffectReport> queryChannelEffectReport(ChannelEffectReportParam channelEffectReportParam) {
		return mapper.queryChannelEffectReport(channelEffectReportParam);
	}

	@Override
	public Page<ChannelEffectReport> queryAllChannelEffectReport(ChannelEffectReportParam channelEffectReportParam, int begin, int end) {
		List<ChannelEffectReport> rows = mapper.queryAllChannelEffectReport(channelEffectReportParam, begin, end);
		int count = mapper.countAllChannelEffectReport(channelEffectReportParam);
		Page page = new Page<ChannelEffectReport>(count, rows);
		page.setPageInfo(count, begin, begin + end);
		return page;
	}

	@Override
	public List<CustomerPremisesDto> selectCommissionByPremises(CustomerPremisesDto entity) {
		return mapper.selectCommissionByPremises(entity);
	}

	@Override
	public List<CustomerPremisesDto> selectCustomerByDay(CustomerPremisesDto entity) {
		return mapper.selectCustomerByDay(entity);
	}

	/**
	 * 获取楼盘报备带看保护时间
	 */
	@Override
	public Calendar getVisitProtectCalendar(Long premisesId, String visitProtect) {
		Calendar calendar = Calendar.getInstance();
		if (StringUtils.isEmpty(visitProtect)) {
			// 未获取到带看保护时间,从楼盘中重新获取
			if (null != premisesId) {
				Premises premises = premisesMapper.selectById(premisesId);
				visitProtect = premises.getVisitProtect();
				if (!StringUtils.isNotEmpty(visitProtect)) {
					visitProtect = "0";
				}
			} else {
				visitProtect = "0";
			}
		}
		Long visitProtectL = Long.valueOf(visitProtect);
		if(visitProtectL > 14400) {//超过10天
		    int days = (int) (visitProtectL / 1440);
		    int lastMinute = (int) (visitProtectL - days * 1440);
            calendar.add(Calendar.DATE, days);
            calendar.add(Calendar.MINUTE, lastMinute);
        } else {
		    calendar.add(Calendar.MINUTE, Integer.parseInt(visitProtect));
        }
		return calendar;
	}

    /**
     * 获取楼盘交易保护时间
     */
    @Override
    public Calendar getSaveDaysCalendar(Long premisesId, String saveDays) {
        Calendar calendar = Calendar.getInstance();
        if (StringUtils.isEmpty(saveDays)) {
            // 未获取到带看保护时间,从楼盘中重新获取
            if (null != premisesId) {
                Premises premises = premisesMapper.selectById(premisesId);
                saveDays = premises.getSaveDays();
                if (!StringUtils.isNotEmpty(saveDays)) {
                    saveDays = "0";
                }
            } else {
                saveDays = "0";
            }
        }
        Long saveDaysL = Long.valueOf(saveDays);
        if(saveDaysL > 14400) {//超过10天
            int days = (int) (saveDaysL / 1440);
            int lastMinute = (int) (saveDaysL - days * 1440);
            calendar.add(Calendar.DATE, days);
            calendar.add(Calendar.MINUTE, lastMinute);
        } else {
            calendar.add(Calendar.MINUTE, Integer.parseInt(saveDays));
        }
        return calendar;
    }

	@Override
	public int hopeVisitOverTime() {
		int result = 0;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar calendar = Calendar.getInstance();
			CustomerPremisesDto cusPreDto = new CustomerPremisesDto();
			cusPreDto.setHopeVisitTimeAfter(calendar.getTime());
			// 报备未发送期望带看到期时间的消息
			String sql = " and (t.hope_visit_msg is null or t.hope_visit_msg = 0)";
			cusPreDto.setSql(sql);
			List<CustomerPremisesDto> cusPreDtoList = mapper.selectDtoListByDto(cusPreDto);
			if (null != cusPreDtoList && cusPreDtoList.size() > 0) {
				String smsTemp = SMSTypeEnum.TYPE_04.getNo();
				DictionaryDto dicDto = new DictionaryDto();
				dicDto.setDicType(smsTemp);
				Dictionary dic = dictionaryService.selectByDto(dicDto);
				if (null != dic) {
					String smsContent = dic.getDicValue();
					String ids = "";
					for (CustomerPremisesDto cusPre : cusPreDtoList) {
						try {
							String hopeVisitMsg = cusPre.getHopeVisitMsg();
							if (StringUtils.isEmpty(hopeVisitMsg) || "0".equals(hopeVisitMsg)) {
								String premisesName = cusPre.getPremisesName();
								String cusName = cusPre.getName();
								String hopeVisitTime = "";
								if (null != cusPre.getHopeVisitTime()) {
									hopeVisitTime = sdf.format(cusPre.getHopeVisitTime());
								}
								String agentMobile = cusPre.getAgentMobile();
								smsContent = String.format(smsContent, premisesName, cusName, hopeVisitTime);
								// 短信不发送, JHSong
								// boolean sendStatus = smsUtil.sendMessage(smsContent, agentMobile);
								boolean sendStatus = false;
								SmsHistoryDto smsHis = new SmsHistoryDto();
								smsHis.setSender(smsUtil.getUserName());
								smsHis.setReceiver(agentMobile);
								smsHis.setContent(smsContent);
								smsHis.setSendStatus(sendStatus ? SendStatusEnum.SUCCESS.getNo() : SendStatusEnum.FAILURE.getNo());
								smsHis.setMerchantId(cusPre.getCompanyId());
								smsHis.setRemark("预约看房超时提醒");
								smsHis.setCreateUserId(0L);
								//添加orderUuid
								smsHistoryService.create(smsHis);
								// 统一修改成功发送的报备短信
								if (sendStatus) {
									ids += cusPre.getId() + ",";
								}
							}
						} catch (Exception e) {
							logger.error("报备: {},发送消息错误,跳过继续: {}", cusPre.getId(), e);
							continue;
						}
					}

					if (StringUtils.isNotEmpty(ids)) {
						ids = ids.substring(0, ids.length() - 1);
						cusPreDto = new CustomerPremisesDto();
						cusPreDto.setIds(ids);
						cusPreDto.setHopeVisitMsg("1");
						mapper.edits(cusPreDto, ids);
					}
				}
			}
			result = 1;
		} catch (Exception ex) {
			logger.error("超时未来访提醒错误: {}", ex);
		}
		return result;
	}

	/**
	 * 方法已作废 移至 CPReportServiceImpl.java
	 * @return
	 */
	@Override
	public int overReportedTime() {
		int result = 0;
		try {
			// 系统当前时间
			Long currentTime = Calendar.getInstance().getTime().getTime();
			CustomerPremisesDto dto = new CustomerPremisesDto();
			dto.setCustomerStatus(CustomerStatusEnum.normal.getNo());
			List<CustomerPremises> lists = customerPremisesMapper.selectListByDto(dto);
			for (CustomerPremises cus : lists) {
				if (cus.getReportPeriodTime() == null || cus.getLookPeriodTime() == null) {
					continue;
				}
				//报备待审状态
                if(!CustomerStatusEnum.normal.getNo().equals(cus.getCustomerStatus())){
				    continue;
                }
                if(!ConfirmStatusEnum.confirm.getNo().equals(cus.getConfirmStatus())){
                    continue;
                }
				Long reportTime = cus.getReportPeriodTime().getTime();
				Long lookTime = cus.getLookPeriodTime().getTime();
				int updateRow = 0;
				String remark = "";
				if (lookTime >= reportTime) {
					// 当期望带看时间>报备保护时间,超过报备保护时间,报备设为无效
					if (currentTime > reportTime) {
						CustomerPremisesDto cusDto = new CustomerPremisesDto();
						cusDto.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
						cusDto.setId(cus.getId());
						cusDto.setUpdateTime(Calendar.getInstance().getTime());
						updateRow = customerPremisesMapper.edit(cusDto);
						remark = "【已过报备保护时间】 报备无效";
					}
				} else if (lookTime <= reportTime) {
					// 当期望带看时间<报备保护时间,超过期望带看时间,报备设为无效
					if (currentTime > lookTime) {
						CustomerPremisesDto cusDto = new CustomerPremisesDto();
						cusDto.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
						cusDto.setId(cus.getId());
						cusDto.setUpdateTime(Calendar.getInstance().getTime());
						updateRow = customerPremisesMapper.edit(cusDto);
						remark = "【已过期望带看时间】 报备无效";
					}
				}
			}
			result = 1;
		} catch (Exception e) {
			logger.error("超过报备保护时间设置无效失败: {}", e);
		}
		return result;
	}

	@Override
	public List<CustomerPremises> selectListByIds(CustomerPremisesDto entity) {
		return mapper.selectListByIds(entity);
	}

	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	@Override
	public int updateByIds(CustomerPremisesDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.updateByIds(entity);
	}

	@Override
	public int flowConfirm() {
		int result = 0;
		try {
			int pageSize = 300;
			int total = 0;
			// 查询报备表中所有报备有效的记录(已到访且未签约或交易失败的数据)
			CustomerPremisesDto dto = new CustomerPremisesDto();
			//新版需求开启此job，为了不影响之前的数据，只取发版后的数据
            String dateString = "2019-05-17 00:00:00";
            Date date= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString);
			dto.setCreateTimeBefore(date);
			dto.setCustomerStatus(CustomerStatusEnum.has_visited.getNo());
			dto.setSql(" t.confirm_status != 3 and t.confirm_status != 4 ");
			total = customerPremisesMapper.count(dto);
			for (int i = 0; i < (total + pageSize - 1) / 300; i++) {
				List<CustomerPremises> lists = customerPremisesMapper.selectMyListByDto(dto, pageSize * i, pageSize);
				for (CustomerPremises cus : lists) {
					// 导入报备不参与自动无效
					if(ReportTypeEnum.type_3.getNo().equals(cus.getReportType())){
						continue;
					}
					FollowUpListDto entity = new FollowUpListDto();
					/**
					 * 复访顺延交易延长时间 V1.5.3(恒信需求)
					 * sangtao
					 */
					Premises premises = premisesMapper.selectById(cus.getPremisesId());
					if(null == premises){
						continue;
					}
					if(premises.getSaveDaysType() == null || TimeUnitTypeEnum.NONE.getNo().equals(String.valueOf(premises.getSaveDaysType()))){
						//premises.setSaveDays(String.valueOf(7*60*24));
						continue;
					}
					if (CustomerStatusEnum.has_visited.getNo().equals(cus.getCustomerStatus()) && ConfirmStatusEnum.confirm.getNo().equals(cus.getConfirmStatus())) {
						//已到访 到认筹的时候需要
						if(new Integer(1).equals(premises.getRepeatDelayDealTime())){
							//允许复访顺延
							entity.setOrders(" visited_count desc,create_time ");
						}
					}
					entity.setCustomerPremisesId(cus.getId());
					entity.setSql("new_customer_status = 6");

					List<FollowUpList> followList = followUpListService.selectListByDto(entity);
					// 到访时间
					Date visitTime = null;
					Boolean visitFlag = true;
					// 认筹时间
					Date payDepositTime = null;
					Boolean payDepositFlag = true;
					// 认购时间
					Date subscribeTime = null;
					Boolean subscribeFlag = true;
					// 签约时间
					Date signTime = null;
					Boolean signFlag = true;
					for (FollowUpList follow : followList) {
						/**
						 * 正常流程： 1,待定(未到访)--》2.到访--》3认筹----》4认购----》签约 跳转流程： 1到访-----》认购 2到访---》签约 3认筹----》签约 0待定-》到访
						 * 1到访-》认筹，2到访-》认购，3到访-》签约 4认筹-》认购，5认筹-》签约 6认购-》签约
						 */
						// 获取到访时间
						if (visitFlag && CustomerStatusEnum.not_visited.getNo().equals(follow.getOldCustomerStatus())
							&& CustomerStatusEnum.has_visited.getNo().equals(follow.getNewCustomerStatus())) {
							visitTime = follow.getCreateTime();
							visitFlag = false;
						}
						if(visitFlag && follow.getOldCustomerStatus().equals(follow.getNewCustomerStatus())
								&& CustomerStatusEnum.has_visited.getNo().equals(follow.getNewCustomerStatus())){
							logger.info("复访记录: ", JSONObject.toJSONString(follow));
							visitTime = follow.getCreateTime();
							visitFlag = false;
						}

						// 认筹到签约
						if (payDepositFlag && ConfirmStatusEnum.payDeposit.getNo().equals(follow.getOldConfirmStatus())
							&& ConfirmStatusEnum.sign.getNo().equals(follow.getNewConfirmStatus())) {
							payDepositTime = follow.getCreateTime();
							payDepositFlag = false;
						}
						// 获取认筹时间（到访到认筹）
						if (payDepositFlag && ConfirmStatusEnum.confirm.getNo().equals(follow.getOldConfirmStatus())
							&& ConfirmStatusEnum.payDeposit.getNo().equals(follow.getNewConfirmStatus())) {
							payDepositTime = follow.getCreateTime();
							payDepositFlag = false;
						}

						// 到访到认购
						if (subscribeFlag && ConfirmStatusEnum.subscribe.getNo().equals(follow.getNewConfirmStatus())
							&& CustomerStatusEnum.has_visited.getNo().equals(follow.getNewCustomerStatus())) {
							subscribeTime = follow.getCreateTime();
							subscribeFlag = false;
						}
						// 获取认购时间(认筹到认购)
						if (subscribeFlag && ConfirmStatusEnum.payDeposit.getNo().equals(follow.getOldConfirmStatus())
							&& ConfirmStatusEnum.subscribe.getNo().equals(follow.getNewConfirmStatus())) {
							subscribeTime = follow.getCreateTime();
							subscribeFlag = false;
						}
						// 到访到签约
						if (signFlag && CustomerStatusEnum.has_visited.getNo().equals(follow.getNewCustomerStatus())
							&& ConfirmStatusEnum.sign.getNo().equals(follow.getNewConfirmStatus())) {
							signTime = follow.getCreateTime();
							signFlag = false;
						}
						// 认筹到签约
						if (signFlag && ConfirmStatusEnum.payDeposit.getNo().equals(follow.getOldConfirmStatus())
							&& ConfirmStatusEnum.sign.getNo().equals(follow.getNewConfirmStatus())) {
							signTime = follow.getCreateTime();
							signFlag = false;
						}
						// 获取签约时间(认购到签约)
						if (signFlag && ConfirmStatusEnum.subscribe.getNo().equals(follow.getOldConfirmStatus())
							&& ConfirmStatusEnum.sign.getNo().equals(follow.getNewConfirmStatus())) {
							signTime = follow.getCreateTime();
							signFlag = false;
						}
					}
					// 查询报备楼盘得到流程保护时间
					String saveDay = premises.getSaveDays();
					Calendar currentDate = Calendar.getInstance();
					// 新版需求增加了单位选项，数据库存的数据单位为分钟
					currentDate.add(Calendar.MINUTE, -Integer.parseInt(saveDay));
					Long currentTime = currentDate.getTime().getTime();
					if (payDepositTime == null && subscribeTime == null && signTime == null) {
						// 到访未认筹
						if (visitTime != null && visitTime.getTime() < currentTime) {
							// 超过流程保护时间（带看保护时间），将报备记录设置为无效
							CustomerPremisesDto customer = new CustomerPremisesDto();
							customer.setId(cus.getId());
							customer.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
							customer.setDisableType(DisableTypeEnum.protected_invalid.getNo());
							customerPremisesMapper.edit(customer);

							// 往跟进表中插入已过到访保护期记录
							insertFlollowUpList(cus);
							continue;
						}
					}
					if (subscribeTime == null && signTime == null) {
						// 已认筹但未认购
						if (payDepositTime != null && payDepositTime.getTime() < currentTime) {
							// 超过流程保护时间，将报备记录设置为无效
							CustomerPremisesDto customer = new CustomerPremisesDto();
							customer.setId(cus.getId());
							customer.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
							customer.setDisableType(DisableTypeEnum.protected_invalid.getNo());
							customerPremisesMapper.edit(customer);
							// 往跟进表中插入已过到访保护期记录
							insertFlollowUpList(cus);
							continue;
						}
					}
					if (signTime == null) {
						// 已认购但未签约
						if (subscribeTime != null && subscribeTime.getTime() < currentTime) {
							// 超过流程保护时间，将报备记录设置为无效
							CustomerPremisesDto customer = new CustomerPremisesDto();
							customer.setId(cus.getId());
							customer.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
							customer.setDisableType(DisableTypeEnum.protected_invalid.getNo());
							customerPremisesMapper.edit(customer);
							// 往跟进表中插入已过到访保护期记录
							insertFlollowUpList(cus);
							continue;
						}
					}
				}
			}
			result = 1;
		} catch (Exception e) {
			logger.error("认筹、认购、签约,判断生效日期是否大于流程等待时间失败: {}", e);
		}
		return result;
	}

	/**
	 * 查询对接人信息 原步骤：根据报备人--》所在部门--》部门对接人
	 *
	 * @param principalIdd
	 * @return
	 */
	private String getPrincipal(Long principalIdd) {
		// Department depart = departmentDao.selectById(pi.getDeptId());
		// if (null != depart && StringUtils.isEmpty(String.valueOf(depart.getPrincipal()))){
		// return null;
		// }
		PartnerInfo partnerInfo = partnerInfoService.selectById(principalIdd);
		if (partnerInfo != null) {
			return partnerInfo.getAccountName();
		}
		return null;
	}

	@Override
	public Long getPricipalId(Long staffId) {
		// TODO Auto-generated method stub
		return customerPremisesMapper.getPricipalId(staffId);
	}

	@Override
	public Map<String, String> getCusStatus(CustomerPremises customerPremises) {
		Map<String, String> map = new HashMap<String, String>();
		if(customerPremises==null) {
			return map;
		}
		// index用于标记报备状态点亮条数，6为最多，全部点亮
		if (CommissionStatusEnum.has_commission.getNo().equals(customerPremises.getCommissionStatus())) {
			//已结佣
			map.put("currentStatus",CommissionStatusEnum.has_commission.getDes());
			map.put("index", "6");
			map.put("value", "1");
		}
		else if (ConfirmStatusEnum.sign.getNo().equals(customerPremises.getConfirmStatus())) {
			//已签约
			map.put("currentStatus",ConfirmStatusEnum.sign.getDes());
			map.put("index", "5");
			map.put("value", "1");
		}
		else if(ConfirmStatusEnum.sign_fail.getNo().equals(customerPremises.getConfirmStatus())&&DisableTypeEnum.SIGN_FAILD.getNo().equals(customerPremises.getDisableType())) {
			//退房
			map.put("currentStatus", DisableTypeEnum.SIGN_FAILD.getDes());
			map.put("index", "5");
			map.put("value", "0");
		}
		else if(ConfirmStatusEnum.subscribe.getNo().equals(customerPremises.getConfirmStatus())) {
			// 认购
			map.put("currentStatus", ConfirmStatusEnum.subscribe.getDes());
			map.put("index", "4");
			map.put("value", "1");
		}
		else if(ConfirmStatusEnum.sign_fail.getNo().equals(customerPremises.getConfirmStatus())&&DisableTypeEnum.SUBSCRIBE_FAILD.getNo().equals(customerPremises.getDisableType())) {
			//退定
			map.put("currentStatus", DisableTypeEnum.SUBSCRIBE_FAILD.getDes());
			map.put("index", "4");
			map.put("value", "0");
		}
		else if (ConfirmStatusEnum.payDeposit.getNo().equals(customerPremises.getConfirmStatus())) {
			// 认筹
			map.put("currentStatus", "已认筹");
			map.put("index", "3");
			map.put("value", "1");
		}
		else if(ConfirmStatusEnum.sign_fail.getNo().equals(customerPremises.getConfirmStatus())&&DisableTypeEnum.PAYDEPOSIT_FAILD.getNo().equals(customerPremises.getDisableType())) {
			//认筹失败
			map.put("currentStatus", DisableTypeEnum.PAYDEPOSIT_FAILD.getDes());
			map.put("index", "3");
			map.put("value", "0");
		}
		else if (CustomerStatusEnum.has_visited.getNo().equals(customerPremises.getCustomerStatus())) {
			// 报备状态为已到访
			map.put("currentStatus",CustomerStatusEnum.has_visited.getDes());
			map.put("index", "2");
			map.put("value", "1");
		}
		else if (CustomerStatusEnum.no_valid.getNo().equals(customerPremises.getCustomerStatus())&&DisableTypeEnum.visit_invalid.getNo().equals(customerPremises.getDisableType())) {
			//到访无效
			map.put("currentStatus",DisableTypeEnum.visit_invalid.getDes());
			map.put("index", "2");
			map.put("value", "0");
		}
		else if (CustomerStatusEnum.not_visited.getNo().equals(customerPremises.getCustomerStatus())) {
			// 未到访
			map.put("currentStatus",CustomerStatusEnum.not_visited.getDes());
			map.put("index", "1");
			map.put("value", "1");
		}
		else if (CustomerStatusEnum.no_valid.getNo().equals(customerPremises.getCustomerStatus())) {
			//报备无效
			if (ProcessStatusEnum.fail.getNo().equals(customerPremises.getProcessStatus())) {
				map.put("currentStatus", "申诉无效");
				map.put("index", "1");
				map.put("value", "0");
			}else {
				map.put("currentStatus",DisableTypeEnum.report_invalid.getDes());
				map.put("index", "1");
				map.put("value", "0");
			}
		}
		else if (CustomerStatusEnum.normal.getNo().equals(customerPremises.getCustomerStatus())) {
			if (ProcessStatusEnum.pending.getNo().equals(customerPremises.getProcessStatus())) {
				map.put("currentStatus", "申诉待审");
				map.put("index", "0");
				map.put("value", "1");
			}else {
				// 报备待审
				map.put("currentStatus", "报备待审");
				map.put("index", "0");
				map.put("value", "1");
			}
		}

		return map;
	}

	// 向跟进表中记录因已过到访保护期时间无效
	private void insertFlollowUpList(CustomerPremises cus) {
		// 往跟进表中插入已过到访保护期记录
		FollowUpListDto fulDto2 = new FollowUpListDto();
		fulDto2.setCustomerPremisesId(cus.getId());
		fulDto2.setOrders("create_time desc");
		List<FollowUpList> list = followUpListService.selectListByDto(fulDto2);
		FollowUpList newFollow = list.get(0);
		FollowUpListDto fulDto = new FollowUpListDto();
		fulDto.setCustomerPremisesId(cus.getId());
		fulDto.setStaffId(cus.getStaffId());
		fulDto.setOldConfirmStatus(newFollow.getNewConfirmStatus());
		fulDto.setNewConfirmStatus(newFollow.getNewConfirmStatus());
		fulDto.setOldCustomerStatus(newFollow.getNewCustomerStatus( ));
		fulDto.setNewCustomerStatus(CustomerStatusEnum.no_valid.getNo());
		fulDto.setOldCommissionStatus(newFollow.getNewCommissionStatus());
		fulDto.setNewCommissionStatus(newFollow.getNewCommissionStatus());
		fulDto.setFollowType(FollowTypeEnum.CHANNEL.getNo());
		fulDto.setRemark("客户超时未交易，转为无效客户");
		followUpListService.create(fulDto);
	}

	@Override
	public Page<CustomerPremisesDto> selectDisCompanyListData(PartnerInfo partnerInfo, Integer begin, Integer end)
		throws TServerException, ParseException {
		CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setCompanyId(partnerInfo.getHigherid());
		premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 根据开发商ID查询楼盘信息
		List<Premises> premisesList = premisesMapper.selectListByDto(premisesDto);
		List<Long> premisesIds = new ArrayList<Long>();
		if (premisesList != null && premisesList.size() > 0) {
			for (Premises premises : premisesList) {
				premisesIds.add(premises.getId());
			}
		} else {
			// 如果不存在驻守楼盘则将楼盘ID当作-1处理,不能查出相关数据
			customerPremisesDto.setPremisesId(-1L);
		}
		customerPremisesDto.setPremisesIds(premisesIds);
		customerPremisesDto.setConfirmStatus(ConfirmStatusEnum.sign.getNo());
		customerPremisesDto.setSql(" and (process_status = 2 or process_status is null)");
		customerPremisesDto.setOrders(" t.create_time asc,t.commission_status desc,t.knot_commission_date asc");
		Integer total = mapper.selectDisCompanyCount(customerPremisesDto);
		List<CustomerPremisesDto> rows = mapper.selectDisCompanyList(customerPremisesDto, begin, end);
		if (rows != null && rows.size() > 0) {
			for (CustomerPremisesDto cusPremisesDto : rows) {
				// 佣金状态
				if (StringUtils.isNotBlank(cusPremisesDto.getCommissionStatus())) {
					if (CommissionStatusEnum.has_commission.getNo().equals(cusPremisesDto.getCommissionStatus())) {
						cusPremisesDto.setCommissionName(CommissionStatusEnum.has_commission.getDes());
					} else {
						cusPremisesDto.setCommissionName(CommissionStatusEnum.no_commission.getDes());
					}
				} else {
					cusPremisesDto.setCommissionName(CommissionStatusEnum.no_commission.getDes());
				}
				// 获取结算周期
				CommissionRules commissionRules = commissionRulesMapper.selectById(cusPremisesDto.getRulesId());
				String settleCycle = "";
				DateFormat fmtDateTime = new SimpleDateFormat("yyyy-MM-dd");
				Calendar today = Calendar.getInstance();
				// 获取待结算佣金条件
				Calendar pendSettleDateBefore = Calendar.getInstance();
				Calendar pendSettleDateAfter = Calendar.getInstance();
				String pendSettleDate = "";
				if (commissionRules != null) {
					settleCycle = commissionRules.getSettlementCycle();
					String commisstionType = commissionRules.getCommissionType();
					Date effectTime = commissionRules.getEffectTime();
					effectTime = fmtDateTime.parse(fmtDateTime.format(effectTime));
					Calendar c = Calendar.getInstance();
					c.setTime(effectTime);
					double days = (today.getTimeInMillis() - c.getTimeInMillis()) / (1000 * 60 * 60 * 24);
					if ("1".equals(settleCycle)) {
						settleCycle = "T+" + settleCycle;
						today.add(Calendar.DAY_OF_MONTH, 1 - (int)days % 1);

						pendSettleDateBefore.add(Calendar.DAY_OF_MONTH, -(int)days % 1);
						pendSettleDateAfter = today;
					} else if ("7".equals(settleCycle)) {
						settleCycle = "T+" + settleCycle;
						today.add(Calendar.DAY_OF_MONTH, 7 - (int)days % 7);

						pendSettleDateBefore.add(Calendar.DAY_OF_MONTH, -(int)days % 7);
						pendSettleDateAfter = today;
					} else if ("15".equals(settleCycle)) {
						settleCycle = "T+" + settleCycle;
						today.add(Calendar.DAY_OF_MONTH, 15 - (int)days % 15);

						pendSettleDateBefore.add(Calendar.DAY_OF_MONTH, -(int)days % 15);
						pendSettleDateAfter = today;
					} else if ("30".equals(settleCycle)) {
						if (CommisionModeEnum.COMMISION_MODE_1.getNo().equals(commisstionType)
							|| CommisionModeEnum.COMMISION_MODE_2.getNo().equals(commisstionType)) {
							settleCycle = "每月10号";
							int dayOfMonth = today.get(Calendar.DAY_OF_MONTH);
							if (dayOfMonth < 10) {
								today.set(Calendar.DAY_OF_MONTH, 10);
								// 还未到结算日期，所以结佣金额的取值应该是上个月的。
								pendSettleDateBefore.add(Calendar.MONTH, -1);
								pendSettleDateBefore.set(Calendar.DAY_OF_MONTH, 10);
								pendSettleDateAfter = today;
							} else {
								today.add(Calendar.MONTH, 1);
								today.set(Calendar.DAY_OF_MONTH, 10);

								pendSettleDateBefore.set(Calendar.DAY_OF_MONTH, 10);
								pendSettleDateAfter = today;
							}
						} else {
							settleCycle = "T+" + settleCycle;
							today.add(Calendar.DAY_OF_MONTH, 30 - (int)days % 30);

							pendSettleDateBefore.add(Calendar.DAY_OF_MONTH, -(int)days % 30);
							pendSettleDateAfter = today;
						}
					} else if ("90".equals(settleCycle)) {
						if (CommisionModeEnum.COMMISION_MODE_1.getNo().equals(commisstionType)
							|| CommisionModeEnum.COMMISION_MODE_2.getNo().equals(commisstionType)) {
							settleCycle = "每季度月首10号";
							List<Integer> quarterList = new ArrayList<Integer>();
							quarterList.add(1);
							quarterList.add(4);
							quarterList.add(7);
							quarterList.add(10);
							// Calendar获取的月份是从0-11，所以这里要加1
							int month = today.get(Calendar.MONTH) + 1;
							if (!quarterList.contains(month)) {
								quarterList.add(month);
								Collections.sort(quarterList);
							}
							int index = quarterList.indexOf(month);
							if (index + 1 == quarterList.size()) {
								month = quarterList.get(0);
								today.add(Calendar.YEAR, 1);
								today.set(Calendar.MONTH, month);
							} else {
								month = quarterList.get(index + 1);
								today.set(Calendar.MONTH, month);
							}
							today.set(Calendar.DAY_OF_MONTH, 10);

							pendSettleDateBefore = today;
							pendSettleDateBefore.add(Calendar.MONTH, -3);
							pendSettleDateBefore.set(Calendar.DAY_OF_MONTH, 1);
							pendSettleDateAfter = today;
						} else {
							settleCycle = "T+" + settleCycle;
							today.add(Calendar.DAY_OF_MONTH, 90 - (int)days % 90);

							pendSettleDateBefore.add(Calendar.DAY_OF_MONTH, -(int)days % 90);
							pendSettleDateAfter = today;
						}
					}
					pendSettleDate = fmtDateTime.format(today.getTime());
				}
				cusPremisesDto.setSettleCycle(settleCycle);
				cusPremisesDto.setPendSettleDate(pendSettleDate);

				// 获取预结算佣金金额
				CustomerPremisesDto searchdto = new CustomerPremisesDto();
				searchdto.setPremisesId(cusPremisesDto.getPremisesId());
				searchdto.setStaffCompanyId(cusPremisesDto.getStaffCompanyId());
				searchdto.setConfirmStatus(ConfirmStatusEnum.sign.getNo());
				searchdto.setSql(" and (commission_status = 2 or commission_status is null) AND cp.rules_id IS NOT NULL");
				try {
					searchdto.setPendSettleDateAfter(pendSettleDateAfter.getTime());
					searchdto.setPendSettleDateBefore(pendSettleDateBefore.getTime());
				} catch (Exception e) {
					// TODO: handle exception
				}
				CustomerPremisesDto cusDto = mapper.getPendCommissionAmount(searchdto);
				if (cusDto != null) {
					cusPremisesDto.setPendCommissionAmount(cusDto.getCommissionAmount() + "");
				}
			}
		}
		Page<CustomerPremisesDto> page = new Page<CustomerPremisesDto>(total, rows);
		return page;
	}

	@Override
	public List<CustomerPremisesDto> getSettlementRecord(CustomerPremisesDto customerPremisesDto) {
		List<CustomerPremisesDto> list = mapper.getSettlementRecord(customerPremisesDto);
		for (CustomerPremisesDto dto : list) {
			if (dto != null && dto.getKnotCommissionDate() != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				dto.setJieYongDate(sdf.format(dto.getKnotCommissionDate()));
			}
			if (dto != null && dto.getKnotCommissionUserId() != null) {
				PartnerInfo partner = partnerInfoMapper.selectById(dto.getKnotCommissionUserId());
				dto.setKnotCommissionUserName(partner.getAccountName());
			}
		}
		return list;
	}

	@Override
	public CustomerPremisesDto getCommissionDetail(CustomerPremisesDto customerPremisesDto) {

		return mapper.getCommissionDetail(customerPremisesDto);
	}

	@Override
	public List<CustomerPremisesDto> getCooCommissionDetail(CustomerPremisesDto customerPremisesDto) throws ParseException {
		List<CustomerPremisesDto> list = mapper.getCooCommissionDetail(customerPremisesDto);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (CustomerPremisesDto cus : list) {
			if (cus.getStaffId() != null) {
				PartnerInfo partner = partnerInfoMapper.selectById(cus.getStaffId());
				cus.setAgentName(partner.getAccountName());
				cus.setAgentMobile(partner.getPhone());
			}
			if (StringUtils.isNotBlank(cus.getCommissionWay())) {
				cus.setCommissionWayName(CommissionWayEnum.getDescByNo(cus.getCommissionWay()));
			}
			if (StringUtils.isNotBlank(cus.getCommissionStatus())) {
				cus.setCommissionStatus(CommissionStatusEnum.getByNo(cus.getCommissionStatus()).getDes());
			}
			FollowUpListDto fDto = new FollowUpListDto();
			fDto.setNewConfirmStatus(ConfirmStatusEnum.sign.getNo());
			fDto.setSql("old_confirm_status!=3");
			List<FollowUpList> followList = followListMapper.selectListByDto(fDto);
			if (followList.size() > 0) {
				cus.setSignTime(sdf.parse(sdf.format(followList.get(0).getCreateTime())));
			}
		}
		return list;
	}

	/**
	 * 查询成交总金额
	 *
	 * @param customerPremisesDto
	 * @return BigDecimal
	 * @author shaoping.jiao
	 */
	@Override
	public BigDecimal queryDealTotalAmount(@Param("customerPremisesDto") CustomerPremisesDto customerPremisesDto) {
		return mapper.queryDealTotalAmount(customerPremisesDto);
	};

	/**
	 * 查询成交总套数
	 *
	 * @param customerPremisesDto
	 * @return int
	 * @author shaoping.jiao
	 */
	@Override
	public int queryDealTotalNumber(@Param("customerPremisesDto") CustomerPremisesDto customerPremisesDto) {
		return mapper.queryDealTotalNumber(customerPremisesDto);
	}

	@Override
	public Page<CustomerPremisesDto> getCommissionPageModel(Long commissionId, Integer beginNum, Integer endNum) throws ParseException {
		// 获取结算周期
		Commission commission = commissionService.selectById(commissionId);
		String settmentleCycle = "";
		if (commission != null) {
			settmentleCycle = commissionService.getRuleSettlementCycle(commission.getCommissionRuleId());
		}
		List<CustomerPremisesDto> list = mapper.myCommissionList(commissionId, beginNum, endNum);
        if(CollectionUtils.isNotEmpty(list)){
            List<Long> partnerIds = list.stream().map(CustomerPremisesDto::getStaffId).collect(Collectors.toList());
            List<Long> agencyCompanyIds = new ArrayList<>();
            Map<Long, PartnerInfo> piMap = new HashMap<>();
            if(CollectionUtils.isNotEmpty(partnerIds)){
                PartnerInfoDto piDto = new PartnerInfoDto();
                piDto.setIds(partnerIds);
                List<PartnerInfo> piList = partnerInfoService.selectListByDto(piDto);
                piMap = piList.stream().collect(Collectors.toMap(PartnerInfo::getId, Function.identity()));
                agencyCompanyIds = piList.stream().map(PartnerInfo::getHigherid).collect(Collectors.toList());
            }

            Map<Long, CompanyDto> companyDtoMap = new HashMap<>();
            if(CollectionUtils.isNotEmpty(agencyCompanyIds)){
                CompanyDto companyDto = new CompanyDto();
                companyDto.setIds(agencyCompanyIds);
                List<CompanyDto> companyDtoList = companyService.selectListByIds(companyDto);
                companyDtoMap = companyDtoList.stream().collect(Collectors.toMap(CompanyDto::getId, Function.identity()));
            }

            for (CustomerPremisesDto cus : list) {
                if (cus.getStaffId() != null) {
                    PartnerInfo partner = piMap.get(cus.getStaffId());
                    if(Objects.nonNull(partner)){
                        cus.setStaffName(partner.getAccountName());
                        cus.setStaffPhone(partner.getPhone());
                        CompanyDto company = companyDtoMap.get(partner.getHigherid());
                        if(Objects.nonNull(company)){
                            cus.setStaffCompanyName(company.getCompanyName());
                        }
                    }
                }
                if (StringUtils.isNotBlank(settmentleCycle)) {
                    cus.setSettlementCycle(settmentleCycle);
                }
                if (StringUtils.isNotBlank(cus.getCommissionWay())) {
                    cus.setCommissionWay(CommissionWayEnum.getDescByNo(cus.getCommissionWay()));
                }
                if (StringUtils.isNotBlank(cus.getCommissionStatus())) {
                    cus.setCommissionStatus(CommissionStatusEnum.getByNo(cus.getCommissionStatus()).getDes());
                } else {
                    cus.setCommissionStatus("待结佣");
                }
                if(Objects.nonNull(cus.getSignTime())){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    cus.setSignTime(sdf.parse(sdf.format(cus.getSignTime())));
                }
            }
        }

		int count = mapper.myCommissionCount(commissionId);
		Page<CustomerPremisesDto> page = new Page<CustomerPremisesDto>(count, list);
		return page;
	}

	/**
	 * 查询报备信息
	 * @param id
	 * @return
	 */
	@Override
	public CustomerPremises selectByIdForLock(Long id) {
		if (id != null) {
			return mapper.selectByIdForLock(id);
		}
		return null;
	}

	/**
	 * 校验手机号是否可以报备  (重复开关校验)
	 * @param mobile
	 * @param premises
	 * @return
	 */
	public boolean checkReportMobile(String mobile, Premises premises, boolean repeatFlag) {
		boolean flag = true;
		//如果打开可重复报备开关返回true
		if(repeatFlag){
			Company company = companyService.selectById(premises.getCompanyId());
			if("1".equals(company.getRepeatReportSwitch())){
				if(new Integer(1).equals(premises.getRepeatReportFlag())){
					return true;
				}
			}
		}
		// 不能重复,判断是否存在到访的待交易数据.
		CustomerPremisesDto cpd = new CustomerPremisesDto();
		cpd.setPremisesId(premises.getId());
		cpd.setMobile(mobile);
		cpd.setSql("customer_status=6 and confirm_status in (0,1,2)");
		List<CustomerPremises> lists = this.selectListByDto(cpd);
		if(null != lists && lists.size()>0){
			return false;
		}
		return flag;
	}

    /**
     * 校验手机号是否存在报备保护期内的数据
     * @param mobile
     * @param premises
     * @return
     */
	public boolean checkReportProtect(String mobile, Premises premises) {
        // 判断是否存在大于当前报备保护时间的报备记录
        CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
        customerPremisesDto.setPremisesId(premises.getId());
        customerPremisesDto.setMobile(mobile);
        Calendar calendar = Calendar.getInstance();
        customerPremisesDto.setReportPeriodTimeBefore(calendar.getTime());
        //customerPremisesDto.setSql("customer_status != -1 and confirm_status != 3 and confirm_status != 4");
        customerPremisesDto.setSql("(customer_status = 0 or customer_status = 10)");
        List<CustomerPremises> cpList = this.selectListByDto(customerPremisesDto);
        if(null != cpList && cpList.size()>0){
            return false;
        }
        return true;
    }

	/**
	 * 到访未交易客户,校验手机号是否重复
	 * @param cusPreId
	 * @param premises
	 * @param mobile
	 * @return
	 */
	public boolean checkVisitRepeat(Long cusPreId, Premises premises, String mobile) {
		boolean flag = false;
		// 获取是否存在大于当前时间的到访保护记录
		CustomerPremisesDto cusPreDto = new CustomerPremisesDto();
		cusPreDto.setPremisesId(premises.getId());
		cusPreDto.setMobile(mobile);
		StringBuilder sb = new StringBuilder();
		sb.append("customer_status = 6 and confirm_status in (0,1,2)");
		sb.append("and (visit_baohu_time > '" + DateUtils.DateToString(Calendar.getInstance().getTime(), DateStyle.YYYY_MM_DD_HH_MM_SS) + "' or visit_baohu_time is null)");
		cusPreDto.setSql(sb.toString());
		List<CustomerPremises> cusPreList = this.selectListByDto(cusPreDto);
		if(null != cusPreList && cusPreList.size()>0){
			for(CustomerPremises repeatCusPre: cusPreList){
				if(repeatCusPre.getId().compareTo(cusPreId) == 0){
					continue;
				}else{
					flag = true;
					break;
				}
			}
		}

		return flag;
	}

	/**
	 * 检验最短报备时间
	 * @param premises
	 * @param hopeTimes
	 * @return
	 */
	public boolean checkSpecialTime(Long hopeTimes,Premises premises){
		if(premises.getSpecialTimeType() == null || TimeUnitTypeEnum.NONE.getNo().equals(premises.getSpecialTimeType())){
			return true;
		}
		Calendar calendar = Calendar.getInstance();
		//最短报备时间限制
		String specialTime = premises.getSpecialTime();
		//该数据存入数据库的时候已经转为分钟，这里无需再转
		calendar.add(Calendar.MINUTE,+Integer.parseInt(specialTime));
		Long specialTimeS = calendar.getTime().getTime();
		if(hopeTimes < specialTimeS) {
			return false;
		}else{
			return true;
		}
	}

	public void noticeImport(int success,int fail,int total,String error,String userId,int current,JSONObject jo,boolean flag){
		// 渠道王迁移，多服务器暂时不支持socket通信
//		NumberFormat numberFormat = NumberFormat.getInstance();
//		numberFormat.setMaximumFractionDigits(0);
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.put("currentSuccess",success);
//		jsonObject.put("currentFail",fail);
//		jsonObject.put("total",total);
//		jsonObject.put("error",error);
//		jsonObject.put("percent",numberFormat.format((float) (current+1) / (float) total * 100));
//		jsonObject.put("report",jo);
//		jsonObject.put("success",flag);
//
//
//		ChannelWebSocketHandler.sendMsg(userId,jsonObject.toJSONString());
	}

	/**
	 * 设置超过报备保护时间
	 */
	@Override
	public int setOverVisitTimeForJob(){
        int result = 0;
		// 查询所有的开启超过到访保护时间自动失效的报备，
		// 判断条件1.楼盘：开启逾期到访时间自动失效功能，楼盘销售状态，楼盘上架状态，2.报备：到访审核状态，（报备审核通过且未交易的）
		List<CustomerPremisesDto> list = mapper.selectCPForVisitJob();
		if(null != list && list.size() > 0) {
			long nowTime = Instant.now().toEpochMilli();

			for(CustomerPremisesDto dto : list){
				try {
					//
					Premises premises = premisesService.getSimpleById(dto.getPremisesId());
					if(premises == null || TimeUnitTypeEnum.NONE.getNo().equals(premises.getVisitProtectType())){
						continue;
					}
					//开始查询时间
					Date hopeVisitTime = dto.getHopeVisitTime();
					if(null == hopeVisitTime) {
						//手机端快速报备时，旧数据没有期望带看时间
						continue;
					}
					long hvTime = hopeVisitTime.toInstant().toEpochMilli();
					//到访延长时间存储时单位为分钟
					String visitProtect = dto.getVisitProtect();
					long vpTime = Long.valueOf(visitProtect) * 60 * 1000;
					//如果到访延长时间开启的话
					long limitTime = hvTime + vpTime;
					//最终截止时间小于当前时间，把报备客户转为无效客户
					if(limitTime < nowTime) {
						CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
						customerPremisesDto.setId(dto.getId());
						customerPremisesDto.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
						//只做跟进，不改备注
//						customerPremisesDto.setRemark("客户超时未到访，转为无效客户");
						result = customerPremisesMapper.edit(customerPremisesDto);
						if(result > 0) {
							//新增跟进记录
							FollowUpListDto followDto = new FollowUpListDto();
							followDto.setStaffId(dto.getStaffId());
							followDto.setCustomerPremisesId(dto.getId());
							followDto.setOldConfirmStatus(dto.getConfirmStatus());
							followDto.setNewConfirmStatus(dto.getConfirmStatus());
							followDto.setOldCustomerStatus(dto.getCustomerStatus());
							followDto.setNewCustomerStatus(CustomerStatusEnum.no_valid.getNo());
							followDto.setRemark("客户超时未到访，转为无效客户");
							followDto.setFollowType(FollowTypeEnum.CHANNEL.getNo());
							followUpListService.create(followDto);
						}
					}
				} catch (Exception e) {
					logger.error("设置超过报备保护时间job异常：{}", e);
				}
			}
		}
		result = 1;
        return result;
    }

    @Override
    public List<CustomerPremisesDto> selectCPForVisitJob(){
		List<CustomerPremisesDto> list = mapper.selectCPForVisitJob();
		return list;
	}

	@Override
	public List<CustomerPremisesVisitCountDto> visitCount(List<Long> customerPremisesIds) {
		return mapper.visitCount(customerPremisesIds);
	}

	/**
	 * 检查楼盘逾期配置，看是否已经逾期
	 * @param dto
	 * @return
	 */
	private boolean checkOverdueConifg(CustomerPremisesDto dto){
		//1.查询 逾期配置overdueConfigMapper
		OverdueConfigDto overdueConfigDto = new OverdueConfigDto();
		overdueConfigDto.setUsable(1);
		overdueConfigDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		overdueConfigDto.setPremisesId(dto.getPremisesId());
		overdueConfigDto.setOrders(" decision_sort ");
		List<OverdueConfig> overdueConfigList = overdueConfigMapper.selectListByDto(overdueConfigDto);
		if(overdueConfigList == null || overdueConfigList.size() == 0){
			return true;
		}
		//2.根据逾期配置节点查询最新的报备记录，跟进记录

		//3.检查逾期情况，并更新报备记录，写跟进
		return false;
	}

	@Async
    @Override
    public Future<String> querySignCount(CustomerPremisesDto customerPremisesDto) {
        return new AsyncResult<String>(String.valueOf(mapper.querySignCount(customerPremisesDto)));
    }

    @Async
    @Override
    public Future<String> querySignAmountCount(CustomerPremisesDto customerPremisesDto) {
    	return new AsyncResult<String>(String.valueOf(mapper.querySignAmountCount(customerPremisesDto)));
    }

    @Async
    @Override
    public Future<String> queryPayDepositCountCount(CustomerPremisesDto customerPremisesDto) {
    	return new AsyncResult<String>(String.valueOf(mapper.queryPayDepositCountCount(customerPremisesDto)));
    }

    @Async
    @Override
    public Future<String> querySubscribeTotalCount(CustomerPremisesDto customerPremisesDto) {
    	return new AsyncResult<String>(String.valueOf(mapper.querySubscribeTotalCount(customerPremisesDto)));
    }

    @Async
    @Override
    public Future<String> queryValidReportCount(CustomerPremisesDto customerPremisesDto) {
    	return new AsyncResult<String>(String.valueOf(mapper.queryValidReportCount(customerPremisesDto)));
    }

    @Async
    @Override
    public Future<String> queryValidVisitCount(CustomerPremisesDto customerPremisesDto) {
    	return new AsyncResult<String>(String.valueOf(mapper.queryValidVisitCount(customerPremisesDto)));
    }

    @Override
    public CustomerPremisesDto selectCompanyByCpId(Long id) {
        return mapper.selectCompanyByCpId(id);
    }

    @Override
    public CustomerPremises selectResetNode( CustomerPremisesDto customerPremisesDto){

	    return mapper.selectResetNode(customerPremisesDto);
    }
	@Override
    public List<CustomerPremises> selectMyListByDto(CustomerPremisesDto customerPremisesDto,int beginNum,int endNum){
		return mapper.selectMyListByDto(customerPremisesDto,beginNum,endNum);
	}

	private Boolean compareTime(Date firstTime, Date secondTime){
		if(firstTime == null || secondTime == null){
			return false;
		}
		return firstTime.after(secondTime);
	}

	@Override
	public int changeCPAdviser(Long premisesId, Long customerPremisesId, String originalAdviser, String newAdviser) {
		return mapper.changeCPAdviser(premisesId, customerPremisesId, originalAdviser, newAdviser);
	}

	/**
	 * 获取即将无效的提醒消息
	 * 开启微信提醒的公司的集合
	 * @param  begin
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getToBeDueRemainderInfo(int begin, int limit, Date date) {
		Map<String, Object> params = new HashMap<>();
		params.put("begin", begin);
		params.put("limit", limit);
		params.put("date", date);
		return mapper.getToBeDueRemainderInfo(params);
	}
	
	/**
	 * 获取已经无效的提醒消息
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getDueRemainderInfo(int begin, int limit, Date date){
		Map<String, Object> params = new HashMap<>();
		params.put("begin", begin);
		params.put("limit", limit);
		params.put("date", date);
		return mapper.getDueRemainderInfo(params);
	}
	
	/**
	 * 根据ID和remainderType，add状态变更提醒次数
	 */
	@Override
	public int addSendTimesById(List<Map<String, Object>> dueRemainderInfos) {
		return mapper.addSendTimesById(dueRemainderInfos);
	}

	@Override
	public int resetConfirm(CustomerPremisesDto customerPremisesDto) {
		return mapper.resetConfirm(customerPremisesDto);
	}

	@Override
	public Page<CustomerPremisesDto> getCpPageModel(CustomerPremisesDto entity, int begin, int end) {
		Integer total = mapper.selectCPForWeappCount(entity);
		List<CustomerPremisesDto> rows = mapper.selectCPForWeappList(entity, begin, end);
		Page<CustomerPremisesDto> msr = new Page<CustomerPremisesDto>(total, rows);
		msr.setPageInfo(total, begin, begin + end);
		return msr;
	}

	public List<ItemInfoDto> selectWHSyncReportList(CustomerPremisesDto customerPremisesDto) {
		return mapper.selectWHSyncReportList(customerPremisesDto);
	}

	public List<InitCPCustomerDto> selectInitCPCustomerList(CustomerPremisesDto customerPremisesDto){
		return mapper.selectInitCPCustomerList(customerPremisesDto);
	}

	@Override
	public List<CustomerPremisesDto> selectImportRepeatListByDto(CustomerPremisesDto customerPremisesDto) {
		return mapper.selectImportRepeatListByDto(customerPremisesDto);
	}

	@Override
	public List<SendVisitListResultDto> getSendVisitList(String lastTime, Long companyId) {
		return mapper.getSendVisitList(lastTime, companyId);
	}

	@Override
	public List<SendIntentionListResultDto> getSendIntentionList(String lastTime, Long companyId) {
		return mapper.getSendIntentionList(lastTime, companyId);
	}
}
